import 'package:dio/dio.dart' as dio;
import 'package:simple_music_app/core/constants/constant.dart';
import 'package:simple_music_app/core/utils/logger.dart';
import 'package:simple_music_app/core/utils/cache_manager.dart';
import 'package:simple_music_app/pages/player_page/models/song_info.dart';

Future<List<SongInfo>> searchSongs(String keyword,
    {int page = 1, int size = 20}) async {
  final client = dio.Dio();
  try {
    AppLogger.d('开始搜索: $keyword, 数量: $size');
    AppLogger.d('请求URL: ${MusicAppConstants.searchApi}');

    final response = await client.get(
      MusicAppConstants.searchApi,
      queryParameters: {
        'msg': keyword,
        'br': 1,
        'type': 'json',
        'num': size,
      },
      options: dio.Options(
        headers: {
          'User-Agent': 'Mozilla/5.0',
          'Accept': 'application/json',
        },
        responseType: dio.ResponseType.json,
      ),
    );

    AppLogger.d('搜索响应状态: ${response.statusCode}');
    AppLogger.d('搜索响应数据: ${response.data}');

    final List<SongInfo> result = [];
    final responseData = response.data;

    if (responseData is Map &&
        responseData.containsKey('code') &&
        responseData['code'] == 200) {
      final data = responseData['data'];
      if (data is List) {
        AppLogger.d('搜索到列表数据，数量: ${data.length}');
        for (var item in data) {
          if (item is Map) {
            result.add(SongInfo.fromJson(item));
          }
        }
      } else if (data is Map && data.containsKey('songs')) {
        final songs = data['songs'];
        if (songs is List) {
          for (var song in songs) {
            result.add(SongInfo.fromJson(song));
          }
        }
      }
    } else {
      throw Exception('API返回错误: ${responseData['message'] ?? '未知错误'}');
    }

    AppLogger.d('最终返回结果数量: ${result.length}');
    return result;
  } catch (e) {
    AppLogger.e('搜索异常', e);
    AppLogger.d('搜索参数: keyword=$keyword, size=$size, page=$page');
    if (e is dio.DioException) {
      if (e.response?.statusCode == 404) {
        throw Exception('API端点不存在，请检查API地址');
      } else if (e.response?.statusCode == 500) {
        throw Exception('服务器内部错误，请稍后再试');
      }
    }
    throw Exception('搜索失败: ${e.toString()}');
  }
}

Future<Map<String, dynamic>> fetchSongInfo(String songId) async {
  final client = dio.Dio();
  final cacheManager = CacheManager();
  try {
    AppLogger.d('开始获取歌曲信息: $songId');

    // 验证songId格式必须为"关键词|歌曲序号"
    final parts = songId.split('|');
    if (parts.length != 2) {
      throw Exception('无效的歌曲ID格式，应为"关键词|歌曲序号"');
    }
    final keyword = parts[0];
    final n = parts[1];

    final response = await client.get(
      '${MusicAppConstants.musicAppNetUrl}',
      queryParameters: {'msg': keyword, 'n': n, 'type': 'json'},
      options: dio.Options(
        headers: {
          'Accept': 'application/json',
        },
        responseType: dio.ResponseType.json,
      ),
    );

    AppLogger.d('歌曲信息响应状态: ${response.statusCode}');
    AppLogger.d('歌曲信息响应数据: ${response.data}');

    if (response.data['code'] != 200 || response.data['music_url'] == null) {
      throw Exception('无法播放该歌曲');
    }

    final musicUrl = response.data['music_url'];
    String playUrl = musicUrl;

    // 检查并下载缓存
    try {
      final cachedPath = await cacheManager.getCachedFilePath(musicUrl);
      if (cachedPath == null) {
        playUrl = await cacheManager.downloadAndCacheFile(musicUrl);
        AppLogger.d('音乐文件已缓存到本地: $playUrl');
      } else {
        playUrl = cachedPath;
        AppLogger.d('使用缓存文件: $playUrl');
      }
    } catch (e) {
      AppLogger.e('缓存处理失败，将使用原始URL', e);
    }

    final result = {
      'url': playUrl,
      'originalUrl': musicUrl,
      'isCached': playUrl != musicUrl,
      'isPaid': false,
      'songInfo': {
        'id': response.data['link']?.toString().split('/').last ?? songId,
        'title': response.data['title'] ?? '未知歌曲',
        'singer': response.data['singer'] ?? '未知歌手',
        'quality': response.data['quality'] ?? '',
        'cover': response.data['cover'] ?? '',
        'lrcUrl': response.data['lrc_url'] ?? '',
        'link': response.data['link'] ?? '',
      }
    };

    AppLogger.d('成功获取歌曲信息: $result');
    return result;
  } catch (e) {
    AppLogger.e('获取歌曲信息异常', e);
    AppLogger.d('歌曲ID: $songId');
    throw Exception('获取播放地址失败: ${e.toString()}');
  }
}
